package org.example.liuy.handler;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;

/**
 * 请求验证处理器 - 责任链模式中的第二个处理器
 * 用于验证基本请求参数
 */
@Slf4j
public class RequestValidationHandler implements HttpHandler {
    private final HttpHandler nextHandler;

    public RequestValidationHandler(HttpHandler nextHandler) {
        this.nextHandler = nextHandler;
    }

    @Override
    public void handle(HttpExchange exchange) throws IOException {
        String method = exchange.getRequestMethod();
        String path = exchange.getRequestURI().getPath();

        if (!Arrays.asList("GET", "POST").contains(method)) {
            sendResponse(exchange, 405, "Method Not Allowed");
            return;
        }

        if (!isValidPath(path)) {
            sendResponse(exchange, 400, "Invalid path format");
            return;
        }

        nextHandler.handle(exchange);
    }

    private boolean isValidPath(String path) {
        return path.matches("/[^/]+/(session|stake|highstakes)");
    }

    private void sendResponse(HttpExchange exchange, int statusCode, String response) throws IOException {
        byte[] responseBytes = response.getBytes();
        exchange.sendResponseHeaders(statusCode, responseBytes.length);
        try (OutputStream os = exchange.getResponseBody()) {
            os.write(responseBytes);
        }
    }
}